﻿using BitBenderGames;
using OWL.Rendering.HRP;
using UnityEngine;
using Yoozoo.Gameplay.City;

public class SetShadowball : MonoBehaviour
{
    public Camera city2dCamera;
    public float Rangerate=1;
    private float k, h,rx, l1,l2,fov1,fov2,rotionX;
    private MobileTouchCamera mobileTouchCamera;
    public float minRangerate = 0.7f;
    public float maxRangerate = 1;
    private float CamZoomMin, CamZoomMax, curCamZoom;
    
    // Start is called before the first frame update
    void Start()
    {        
        if (city2dCamera == null) return;
        rotionX=city2dCamera.transform.eulerAngles.x;

        rx=city2dCamera.transform.eulerAngles.x*(Mathf.PI*2/360);
        fov1=city2dCamera.fieldOfView*(Mathf.PI*2/360);
        fov2=2*Mathf.Atan(  Mathf.Tan(fov1/2)*Screen.width/Screen.height);
        l1 = (1*  Mathf.Tan(Mathf.PI/2-rx+fov1/2)  )- (1/Mathf.Tan(Mathf.PI/2-rx-fov1/2) );
        l2=(1/Mathf.Sin(rx-fov1/2))*Mathf.Tan(fov2/2);
        //UnityEngine.Debug.Log(city2dCamera.transform.position.y+"  ?????"+city2dCamera.transform.eulerAngles.x);
        k=Mathf.Sqrt(l1*l1+l2*l2);
        if (CityManager.Instance && CityManager.Instance.mobileTouchCamera)
        {
            mobileTouchCamera = CityManager.Instance.mobileTouchCamera;
            CamZoomMin = mobileTouchCamera.CamZoomMin;
            CamZoomMax = mobileTouchCamera.CamZoomMax;
        }
        
    }

    // Update is called once per frame
    void Update()
    {

        if (city2dCamera == null) return;
        
        if(city2dCamera.transform.eulerAngles.x!=rotionX){
           
            rotionX=city2dCamera.transform.eulerAngles.x;
            if (city2dCamera == null) return;
            rx=city2dCamera.transform.eulerAngles.x*(Mathf.PI*2/360);
            fov1=city2dCamera.fieldOfView*(Mathf.PI*2/360);
            fov2=2*Mathf.Atan(  Mathf.Tan(fov1/2)*Screen.width/Screen.height);
            l1 = (1*  Mathf.Tan(Mathf.PI/2-rx+fov1/2)  )- (1/Mathf.Tan(Mathf.PI/2-rx-fov1/2) );
            l2=(1/Mathf.Sin(rx-fov1/2))*Mathf.Tan(fov2/2);
            //UnityEngine.Debug.Log(city2dCamera.transform.position.y+"  ?????"+city2dCamera.transform.eulerAngles.x);
            k=Mathf.Sqrt(l1*l1+l2*l2);
        }

        if (city2dCamera.transform.position.y == h) return;
        
        Rangerate = 1;
        h =city2dCamera.transform.position.y;
        if (mobileTouchCamera)
        {
            curCamZoom = mobileTouchCamera.CamZoom;
            Rangerate = (curCamZoom - CamZoomMin)/ (CamZoomMax - CamZoomMin) * (maxRangerate - minRangerate)  + minRangerate;
            Rangerate = Rangerate < minRangerate ? minRangerate : Rangerate;
            Rangerate = Rangerate > maxRangerate ? maxRangerate : Rangerate;
        }
        
        //  UnityEngine.Debug.Log(rx/(Mathf.PI*2/360)+"  ?"+fov1/(Mathf.PI*2/360)+"   "+fov2/(Mathf.PI*2/360)+"   "+l1 +"  "+l2 + "   "+h);
        
        city2dCamera.GetCameraData().m_CustomShadowMapRadius=h*k*Rangerate;

    }
}
